<template>
  <div ref="chartRef" style="width: 100%; height: 300px"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { getRoomStatistics } from '@/api/statistics'

const chartRef = ref(null)
let myChart = null

const roomStats = ref({})

/* 获取房态数据 */
function getRoomStats() {
  getRoomStatistics().then(res => {
    if (res.code === 200) {
      roomStats.value = res.data
      initChart()
    }
  })
}

/* 初始化图表 */
function initChart() {
  const option = {
    title: {
      text: `${roomStats.value.occupancyRate}%`,
      subtext: '入住率',
      left: 'center',
      top: 'center',
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold'
      },
      subtextStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { 
            value: roomStats.value.occupancyRate || 0, 
            name: '已租',
            itemStyle: { color: '#67C23A' }
          },
          { 
            value: 100 - (roomStats.value.occupancyRate || 0), 
            name: '空置',
            itemStyle: { color: '#909399' }
          }
        ]
      }
    ]
  }

  myChart.setOption(option)
}

onMounted(() => {
  myChart = echarts.init(chartRef.value)
  getRoomStats()
  
  window.addEventListener('resize', () => {
    myChart.resize()
  })
})

onUnmounted(() => {
  if (myChart) {
    myChart.dispose()
  }
  window.removeEventListener('resize', () => {
    myChart.resize()
  })
})
</script>
